import { defineStore } from 'pinia';
import apiClient from '@/api';
import router from '@/router';

export const useAuthStore = defineStore('auth', {
    state: () => ({
        isLoggedIn: false,
        user: null, // 将来可以存放用户信息，例如 { name: '...' }
    }),
    actions: {
        /**
         * 登录
         * @param {object} credentials - { access_key_id, secret_access_key }
         */
        async login(credentials) {
            try {
                const response = await apiClient.post('/api/v1/auth/login', credentials);
                this.isLoggedIn = true;
                this.user = response.data.user;
                return true; // 返回 true 表示登录成功
            } catch (error) {
                this.isLoggedIn = false;
                this.user = null;
                // 向上抛出错误，让组件可以捕获并显示
                throw new Error(error.response?.data?.error || '登录失败，请检查网络连接');
            }
        },

        /**
         * 登出
         */
        async logout() {
            try {
                // 通知后端清除会话
                await apiClient.post('/api/v1/auth/logout');
            } finally {
                // 无论后端是否成功，前端都必须清除状态并跳转
                this.isLoggedIn = false;
                this.user = null;
                // 登出后重定向到登录页
                router.push({ name: 'Login' });
            }
        },

        /**
         * 检查当前会话状态 (通常在应用加载时调用)
         */
        async checkAuthStatus() {
            try {
                const response = await apiClient.get('/api/v1/auth/status');
                this.isLoggedIn = response.data.isLoggedIn;
                this.user = response.data.user;
                return this.isLoggedIn;
            } catch (error) {
                // 如果检查状态的API失败 (例如session过期或网络错误)，则视为未登录
                this.isLoggedIn = false;
                this.user = null;
                return false;
            }
        }
    }
});